<template>

  <!-- <el-breadcrumb separator=">" style="margin-bottom: 20px;font-size: 20px;">
        <el-breadcrumb-item :to="{ path: '/main' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/Courses/CourseList' }">课程管理</el-breadcrumb-item>
        <el-breadcrumb-item>课程列表</el-breadcrumb-item>
    </el-breadcrumb> -->
  <div>
    <el-button type="primary" style="margin-left: 16px" @click="drawer = true">
      新增
    </el-button>
    <el-button type="danger" style="margin-left: 16px" @click="deleteRang()">
      删除
    </el-button>
  </div>

  <el-form :inline="true" :model="forms" style="margin-top: 20px;">
    <el-form-item label="商品名称">
      <el-input v-model="forms.commodityName" placeholder="输入进行查询" style="width: 100px;font-size: 13px;" clearable
        @change="getCourses()" />
    </el-form-item>
    <el-form-item label="生产批次">
      <el-input v-model="forms.productionLot" placeholder="输入进行查询" style="width: 100px;font-size: 13px;" clearable
        @change="getCourses()" />
    </el-form-item>
    <el-form-item label="保质期(天)">
      <el-input v-model="forms.shelfLife" placeholder="输入进行查询" style="width: 100px;font-size: 13px;" clearable
        @change="getCourses()" />
    </el-form-item>
    <el-form-item label="生产许可证号">
      <el-input v-model="forms.manufacturingLicense" placeholder="输入进行查询" style="width: 100px;font-size: 13px;"
        clearable @change="getCourses()" />
    </el-form-item>
    <el-form-item label="生产企业">
      <el-input v-model="forms.enterpriseName" placeholder="输入进行查询" style="width: 100px;font-size: 13px;" clearable
        @change="getCourses()" />
    </el-form-item>
    <el-form-item label="创建人">
      <el-input v-model="forms.createBy" placeholder="输入进行查询" style="width: 100px;font-size: 13px;" clearable
        @change="getCourses()" />
    </el-form-item>
    <el-form-item label="创建时间">
      <el-input v-model="forms.createDate" placeholder="输入进行查询" style="width: 100px;font-size: 13px;" clearable
        @change="getCourses()" />
    </el-form-item>
  </el-form>
  <!-- v-loading="form.isLoading" -->
  <el-table :data="courses" style="width: 100%" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55" />
    <el-table-column prop="id" label="序号" align="center">
      <template #default="scope">
        {{ scope.$index + 1 }}
      </template>
    </el-table-column>
    <el-table-column prop="commodityName" label="商品名称" align="center" sortable />
    <el-table-column prop="productionLot" label="生产批次" align="center" />
    <el-table-column prop="shelfLife" label="保质期(天)" align="center" />
    <el-table-column prop="manufacturingLicense" label="生产许可证号" align="center" />
    <el-table-column prop="enterpriseName" label="生产企业" align="center" />
    <el-table-column prop="createBy" label="创建人" align="center" />
    <el-table-column prop="createDate" label="创建时间" align="center">
      <template #default="scope">
        {{ scope.row.createDate.substring(0, 10) }}
      </template>
    </el-table-column>
    <el-table-column label="操作" fixed="right" width="300px">
      <template #default="scope">
        <el-button type="primary"
          @click="details(scope.row.id, scope.row.productionLot, scope.row.manufacturingLicense)"
          style="width: 40px;font-size: 10px;">详情</el-button>
        <el-button type="danger" @click="deleteData(scope.row.id)" style="width: 40px;font-size: 10px;">删除</el-button>
        <el-button type="warning" style="width: 60px;font-size: 10px;"
          @click="NpoMage(scope.row.inspection)">导出溯源码</el-button>
        <el-button type="primary" @click="updateDate(scope.row.id)" style="width: 40px;font-size: 10px;">编辑</el-button>
      </template>
    </el-table-column>
  </el-table>

  <div style="margin-top: 10px;">
    <table>
      <tr>
        <td>
          <el-pagination v-model:current-page="forms.pageIndex" v-model:page-size="forms.pageSize"
            :page-sizes="[3, 5, 8, 10]" :background="true" layout="total, slot" next-text="下一页" prev-text="上一页"
            :hide-on-single-page="forms.recordCount == 0" :total="forms.recordCount" @size-change="handleSizeChange"
            @current-change="handleCurrentChange">
            <span>,每页{{ forms.pageSize }}条,当前第{{ forms.pageIndex }}/{{ form.spageCount }}页</span>
          </el-pagination>
        </td>
        <td>
          <el-pagination v-model:current-page="forms.pageIndex" v-model:page-size="forms.pageSize"
            :page-sizes="[3, 5, 8, 10]" :background="true" layout="slot, sizes, prev, pager" next-text="下一页"
            prev-text="上一页" :hide-on-single-page="forms.recordCount == 0" :total="forms.recordCount"
            @size-change="handleSizeChange" @current-change="handleCurrentChange">
            <el-button class="btn-prev" :disabled="forms.pageIndex == 1" @click="handleCurrentChange(1)">首页</el-button>
          </el-pagination>
        </td>
        <td>
          <el-pagination v-model:current-page="forms.pageIndex" v-model:page-size="forms.pageSize"
            :page-sizes="[3, 5, 8, 10]" :background="true" layout=" slot,next, jumper" next-text="下一页" prev-text="上一页"
            :hide-on-single-page="forms.recordCount == 0" :total="forms.recordCount" @size-change="handleSizeChange"
            @current-change="handleCurrentChange">
            <el-button class="btn-prev" :disabled="forms.pageIndex == forms.pageCount"
              @click="handleCurrentChange(forms.pageCount)">尾页</el-button>
          </el-pagination>
        </td>
      </tr>
    </table>

  </div>

  <div>

    <el-drawer v-model="drawer" title="溯源添加" size="30%">
      <div>
        <!-- form表单 -->
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="form" :rules="rules" label-width="auto"
          class="demo-ruleForm" :size="formSize" status-icon>
          <el-form-item label="商品名称" prop="commodityId">
            <el-select v-model="form.commodityId" placeholder="请选择商品">
              <el-option v-for="item in goodslist" :key="item.id" :label="item.commodityName" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="生产批次" prop="productionLot">
            <el-input v-model="form.productionLot" />
          </el-form-item>
          <el-form-item label="保质期（天）" prop="shelfLife">
            <el-input v-model="form.shelfLife" />
          </el-form-item>
          <el-form-item label="生产许可证号" prop="manufacturingLicense">
            <el-input v-model="form.manufacturingLicense" />
          </el-form-item>
          <el-form-item label="生产企业" prop="enterpriseName">
            <el-input v-model="form.enterpriseName" />
          </el-form-item>
          <el-form-item label="封面图" prop="traceabilityPicture">
            <el-upload class="avatar-uploader" action="http://localhost:44228/api/Goods/UploadFile"
              :show-file-list="false" :on-success="handleAvatarSuccess">
              <img v-if="form.traceabilityPicture" :src="picture" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
              确认
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            <el-button @click="drawer = false">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
    <el-drawer v-model="drawer2" title="溯源修改" size="30%">
      <div>
        <!-- form表单 -->
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="form1" :rules="rules" label-width="auto"
          class="demo-ruleForm" :size="formSize" status-icon>
          <el-form-item label="商品名称" prop="commodityId">
            <el-select v-model="form1.commodityId" placeholder="请选择商品">
              <el-option v-for="item in goodslist" :key="item.id" :label="item.commodityName" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="生产批次" prop="productionLot">
            <el-input v-model="form1.productionLot" />
          </el-form-item>
          <el-form-item label="保质期（天）" prop="shelfLife">
            <el-input v-model="form1.shelfLife" />
          </el-form-item>
          <el-form-item label="生产许可证号" prop="manufacturingLicense">
            <el-input v-model="form1.manufacturingLicense" />
          </el-form-item>
          <el-form-item label="生产企业" prop="enterpriseName">
            <el-input v-model="form1.enterpriseName" />
          </el-form-item>
          <el-form-item label="封面图" prop="traceabilityPicture">
            <el-upload class="avatar-uploader" action="http://localhost:44228/api/Goods/UploadFile"
              :show-file-list="false" :on-success="handleAvatarSuccess1">
              <img v-if="form1.traceabilityPicture" :src="files + form1.traceabilityPicture" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm1(ruleFormRef)">
              保存
            </el-button>
            <el-button @click="resetForm1(ruleFormRef)">重置</el-button>
            <el-button @click="drawer2 = false">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
  </div>
  <div>
    <!-- 导出源码 -->
    <el-dialog v-model="Visible" title="导出设置" width="500" :before-close="handleClose">
      <template #footer>
        <div>
          <input v-model="text" placeholder="输入文本生成二维码地址" />
          <button @click="generateQRCodeURL">生成二维码地址</button>
          <button v-if="qrCodeURL" @click="downloadTXT">下载文本文件</button>
          <div v-if="qrCodeURL">
            <p>二维码地址：<a :href="qrCodeURL" target="_blank">点击查看二维码</a></p>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>

</template>


<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue'
//form表单
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
//上传图片变量
const files = ref("http://localhost:44228/Image/")
//抽屉
import type { DrawerProps } from 'element-plus'
const drawer = ref(false)
const drawer2 = ref(false)
const direction = ref<DrawerProps['direction']>('rtl')
const router = useRouter();
const forms = reactive({
  commodityName: "",
  productionLot: "",
  shelfLife: 0,
  manufacturingLicense: "",
  enterpriseName: "",
  createBy: "",
  createDate: null,
  pageIndex: 1,
  pageSize: 15,
  recordCount: 1,
  pageCount: 1
})
//添加表单
const form = reactive({
  commodityId: '',
  productionLot: "",
  shelfLife: 0,
  manufacturingLicense: "",
  enterpriseName: "",
  traceabilityPicture: "",
  inspection: "",
})
const form1 = reactive({
  id: 0,
  commodityId: '',
  productionLot: "",
  shelfLife: 0,
  manufacturingLicense: "",
  enterpriseName: "",
  traceabilityPicture: "",
  inspection: "",
  createBy: "string",
  createDate: null,
  isDel: false,
})
//自动生成
const getCurrentDateString = () => {
  const today = new Date();
  const year = today.getFullYear();
  const month = String(today.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1
  const day = String(today.getDate()).padStart(2, '0');
  form.productionLot = `${year}${month}${day}`;
  console.log(form.productionLot)
  const shuzi = Math.floor(Math.random() * 10000000000);
  form.manufacturingLicense = "SC" + shuzi;
}
const alls = ref([])//全
const ids = ref([])//选中
const idss = ref(0)
//多选
const handleSelectionChange = (val: any) => {
  alls.value = val
  alls.value.forEach(item => {
    ids.value.push(item.id)
  })
}

//添加
const rules = reactive<FormRules>({
  name: [
    { required: true, message: 'Please input Activity name', trigger: 'blur' },
    { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
  ],
  sd: [
    { required: true, message: 'Please input Activity name', trigger: 'blur' },
    { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
  ],
})
//添加
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      axios.post("Goods/AddProduc", form).then(response => {
        console.log(response.data)
        if (response.data.data == 1) {
          ElMessage({
            message: response.data.msg,
            type: 'success',
          })
          form.value = ''
          drawer.value = false
          getCourses();
        } else {
          ElMessage.error(response.data.msg)
        }
      })
      console.log('submit!')
    } else {
      console.log('error submit!', fields)
    }
  })
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

//商品下拉框
const goodslist = ref([]);
const getGoodslist = () => {
  axios.get("Goods/GetCommodity").then(response => {
    goodslist.value = response.data.data;
  })
}
const NpoMage = (mage: string) => {
  Visible.value = true;
  text.value = mage;
}
//导出溯源码
//溯源码
import QRCode from 'qrcode'
const Visible = ref(false)
//溯源码
//生成二维码
const text = ref('');
const qrCodeURL = ref('');
const generateQRCodeURL = () => {
  QRCode.toDataURL(text.value)
    .then((url) => {
      qrCodeURL.value = url;
    })
    .catch((err) => {
      console.error(err);
    });
};
// 导出文本文件
const downloadTXT = () => {
  const blob = new Blob([qrCodeURL.value], { type: 'text/plain;charset=utf-8' });
  const link = document.createElement('a');
  link.href = URL.createObjectURL(blob);
  link.download = 'qrcode-url.txt'; // 你可以修改文件名
  link.click();
};

//上传图片
//上传
const picture = ref("")
const pictures = ref("")
const handleAvatarSuccess = (file: any) => {
  form.traceabilityPicture = file.data
  picture.value = "http://localhost:44228/Image/" + form.traceabilityPicture
  console.log(form.traceabilityPicture)
}
const handleAvatarSuccess1 = (file: any) => {
  form1.traceabilityPicture = file.data
  pictures.value = "http://localhost:44228/Image/" + form1.traceabilityPicture
  console.log(form1.traceabilityPicture)
}
const beforeAvatarUpload = () => {
  // if (rawFile.type !== 'image/jpeg') {
  //   ElMessage.error('Avatar picture must be JPG format!')
  //   return false
  // } else if (rawFile.size / 1024 / 1024 > 2) {
  //   ElMessage.error('Avatar picture size can not exceed 2MB!')
  //   return false
  // }
  // return true
}
//分页
const handleSizeChange = (val: number) => {
  forms.pageSize = val;
  getCourses();
}
const handleCurrentChange = (val: number) => {
  forms.pageIndex = val;
  getCourses();
}
//钩子函数
onMounted(() => {
  getCourses();
  getGoodslist();
  getCurrentDateString();
})
//显示
const courses = ref([]);
const getCourses = () => {
  axios.post("Goods/GetProducOutputs", forms)
    .then(res => {
      courses.value = res.data.data.data;
      forms.recordCount = res.data.data.total;
      forms.pageCount = res.data.data.pageCount;
    })
    .catch(error => {
      console.log(error)
    })

}

//删除
const deleteData = (id: number) => {
  ElMessageBox.confirm(
    '确认要删除吗?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      axios.get("Goods/DeletePro?id=" + id)
        .then(res => {
          if (res.data.code == 1) {
            ElMessage.success("删除成功");
            getCourses();
          }
          else {
            ElMessage.error("删除失败");
          }

        })
        .catch(() => {
          ElMessage.error("取消删除");
        })
    })
}
//批量删除
const deleteRang = () => {
  ElMessageBox.confirm(
    '确认要批量删除吗?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      axios.post("Goods/DeleteRang", ids.value)
        .then(res => {
          if (res.data.code == 1) {
            ElMessage.success("删除成功");
            getCourses();
          }
          else {
            ElMessage.error("删除失败");
          }

        })
        .catch(() => {
          ElMessage.error("取消删除");
        })
    })
}
//反填
const updateDate = (id: number) => {
  drawer2.value = true
  axios.get("Goods/FindPro?id=" + id)
    .then(res => {
      form1.commodityId = res.data.data.commodityId;
      form1.productionLot = res.data.data.productionLot;
      form1.shelfLife = res.data.data.shelfLife;
      form1.manufacturingLicense = res.data.data.manufacturingLicense;
      form1.enterpriseName = res.data.data.enterpriseName;
      form1.traceabilityPicture = res.data.data.traceabilityPicture;
      form1.inspection = res.data.data.inspection;
      form1.id = res.data.data.id;
      form1.createBy = res.data.data.createBy;
      form1.createDate = res.data.data.createDate;
      form1.isDel = res.data.data.isDel;
    })
    .catch(error => {
      console.log(error)
    })
}
//修改
const submitForm1 = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      axios.post("Goods/UpdatePro", form1).then(response => {
        console.log(response.data)
        if (response.data.code == 1) {
          ElMessage({
            message: response.data.msg,
            type: 'success',
          })
          form1.value = ''
          drawer2.value = false
          getCourses();
        } else {
          ElMessage.error(response.data.msg)
        }
      })
      console.log('submit!')
    } else {
      console.log('error submit!', fields)
    }
  })
}
const resetForm1 = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
//修改跳转页面
const details = (id: number, productionLot: string, manufacturingLicense: string) => {
  router.push({
    name: "RabbitDetails",
    query: {
      id: id,
      productionLot: productionLot,
      manufacturingLicense: manufacturingLicense
    }
  })
}


</script>
<style scoped>
.avatar-uploader .avatar {
  width: 150px;
  height: 150px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  text-align: center;
}
</style>